<template>
  <div class="SSML" id="SSML">
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="选择星座">
        <el-select
          v-model="form.xingzuoSelect"
          placeholder="请选择星座"
          @change="changeSelect"
        >
          <el-option
            v-for="each_xz in all_xingzuo"
            :label="each_xz.value"
            :value="each_xz.key"
            :key="each_xz.name"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <hr />
    <div id="xingzuo_lable">
      <el-tabs>
        <el-tab-pane label="今日运势">
          <el-input
            type="textarea"
            name="name"
            rows="8"
            cols="80"
            v-model="content.ri"
          ></el-input>
        </el-tab-pane>
        <el-tab-pane label="本周运势">
          <el-input
            type="textarea"
            name="name"
            rows="8"
            cols="80"
            v-model="content.zhou"
          ></el-input>
        </el-tab-pane>
        <el-tab-pane label="本月运势">
          <el-input
            type="textarea"
            name="name"
            rows="8"
            cols="80"
            v-model="content.yue"
          ></el-input>
        </el-tab-pane>
        <el-tab-pane label="本年运势">
          <el-input
            type="textarea"
            name="name"
            rows="8"
            cols="80"
            v-model="content.nian"
          ></el-input>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import $ from "jquery";
import XingZuoVue from './XingZuo.vue';
export default {
  name: "SSML",
  data() {
    return {
      base_url: "https://www.susanmiller.cn",
      message: "苏珊米勒",
      rep_data: "苏珊米勒",
      xingzuo_suffix: "ssml_html",
      ttl_key: "ssml_time",
      common_key: "ssml_key",
      xingzuo_data_key: "ssml_data",
      cache_key_daily:'ssml_daily',
      cache_key_daily_before:"ssml_daily_before",
      cache_key_weekly:'ssml_weekly',
      cache_key_weekly_before:'ssml_weekly_before',
      cache_key_monthly:'ssml_monthly',
      cache_key_yearly:'ssml_yearly',
      content: {
        ri: "",
        zhou: "",
        yue: "",
        nian: "",
      },
      form: {
        xingzuoSelect: "处女座",
      },
      all_xingzuo: [
        {
          key: "白羊座",
          value: "白羊座 (3.21-4.19)",
        },
        {
          key: "金牛座",
          value: "金牛座 (4.20-5.20)",
        },
        {
          key: "双子座",
          value: "双子座 (5.21-6.21)",
        },
        {
          key: "巨蟹座",
          value: "巨蟹座 (6.22-7.22)",
        },
        {
          key: "狮子座",
          value: "狮子座 (7.23-8.22)",
        },
        {
          key: "处女座",
          value: "处女座 (8.23-9.22)",
        },
        {
          key: "天秤座",
          value: "天秤座 (9.23-10.23)",
        },
        {
          key: "天蝎座",
          value: "天蝎座 (10.24-11.22)",
        },
        {
          key: "射手座",
          value: "射手座 (11.23-12.21)",
        },
        {
          key: "摩羯座",
          value: "摩羯座 (12.22-1.19)",
        },
        {
          key: "水瓶座",
          value: "水瓶座 (1.20-2.18)",
        },
        {
          key: "双鱼座",
          value: "双鱼座 (2.19-3.20)",
        },
      ],
    };
  },
  methods: {
    flushDataFromWebSide() { // 从网站上获取数据
      console.log("flushDataFromWebSide");
      //从首页获取日/周/月/年列表页的URL
      this.$axios.get(this.base_url).then((response) => {
        var el = $(response.data);
        var div_homenav = $('div.home_nav', el)
        var resultArray = new Array();
        $('h2',div_homenav).each(function(){
          resultArray.push($('a',this).attr('href'))
        })
        var ri_url = this.base_url+resultArray[0];
        var zhou_url = this.base_url+resultArray[1];
        var yue_url = this.base_url+resultArray[2];
        var nina_url = this.base_url+resultArray[3];
        this.getIndexPostCoutentFormPostListUrl(this.cache_key_daily,ri_url) // 日数据
        this.getIndexPostCoutentFormPostListUrl(this.cache_key_daily_before,ri_url,1)
        this.getIndexPostCoutentFormPostListUrl(this.cache_key_weekly,zhou_url) // 周数据
        this.getIndexPostCoutentFormPostListUrl(this.cache_key_weekly_before,zhou_url,1) // 周数据
        this.getRecommentPostUrlFromPostListUrl(this.cache_key_monthly,yue_url)
        this.getRecommentPostUrlFromPostListUrl(this.cache_key_yearly,nina_url)
        // 设置数据更新时间
        localStorage.setItem(this.ttl_key,new Date().getTime())
      });
    },
    zipTwoArrayWithIndex(keyArr,valueArray){//通过索引位置将两个数组压缩成kv对象
      var len = keyArr.length;
      var obj = new Object();
      for(var i=0;i <= len;i++){
        obj[keyArr[i]]=valueArray[i];
      }
      return obj;
    },
    getIndexPostCoutentFormPostListUrl(cacheKey,url,index=0){//通过文章列表页面url获取到第一篇文章的内容
      this.$axios.get(url).then((response) => {
        var el = $(response.data);
        //获取文章列表第一个,当前日的文章URL
        var post_url = $('a.opt_img',el).slice(index).first().attr('href')
        this.$axios.get(post_url).then((responseData) => {
          var respData = $(responseData.data);
          //获取文章列表第一个,当前日的文章URL
          var header = $('div.view_title',respData).find('h1').html();
          console.log('header\t'+header);
          var index=0;
          var xingzuoName = new Array();
          var xingzuoNeirong = new Array();
          $('div#VIEW_CNT',respData).find('p').slice(1).each(function(){
            if(index%2==0){
              xingzuoName.push($(this).html().replace(/[(<strong>)(</strong>)\s]/g, ''))
            }else{
              xingzuoNeirong.push($(this).html())
            }
            index+=1;
          });
          const resultData =  this.zipTwoArrayWithIndex(xingzuoName,xingzuoNeirong);
          var result = new Object();
          result.title = header;
          result.data = resultData;
          localStorage.setItem(cacheKey,JSON.stringify(result));
          console.log("getFirstPostCoutentFormPostListUrl\t"+cacheKey);
          return result;
        });
      });
    },
    getRecommentPostUrlFromPostListUrl(cacheKey,url){
      this.$axios.get(url).then((response) => {
        var el = $(response.data);
        var result = new Array();
        result.push("文章列表页:"+url+"\n\nTop5文章详情页:")
        //获取文章列表第一个,当前日的文章URL
        $('div.list_option',el).slice(0,5).each(function(){
          var href = $(this).find('h3').find('a').attr('href')
          var html = $(this).find('h3').find('a').html()
          result.push(html+"\n"+href)
        });
        localStorage.setItem(cacheKey,result.join('\n'));
      });
    },
    getMonthlyData(url) {
      //获取月数据
      console.log('yue:'+url);
      localStorage.setItem(this.cache_key_monthly,url);
    },
    getYearlyData(url) {
      //获取年数据
      console.log('nian:'+url);
      localStorage.setItem(this.cache_key_yearly,url);
      //TODO
    },
    changeSelect() {
      localStorage.setItem("xingzuo", this.form.xingzuoSelect);
      this.getXingZuoData(this.form.xingzuoSelect);
    },
    getDefaultXingZuoSelectedValue() {
      // 获取<缓存|默认>星座选择框数据
      var select_value = localStorage.getItem("xingzuo");
      if (select_value == null || typeof select_value == "undefined") {
        select_value = "白羊座";
      }
      return select_value;
    },
    getLocalData(xingzuo) {
      // 从缓存中获取数据
      var d = new Date();
      var ttl_time = localStorage.getItem(this.ttl_key);
      if (ttl_time == null || typeof ttl_time == "undefined") {
        ttl_time = -1;
      }
      var sub = d.getTime() - ttl_time;
      // 缓存时间
      console.log("getLocalData\t"+sub);
      if (sub > 300000) {//300000
        this.flushDataFromWebSide();
      }
      console.log("getLocalData from local");
      //日
      var riDataMap = localStorage.getItem(this.cache_key_daily);
      let riData = JSON.parse(riDataMap);
      //日-before
      var riBeforeDataMap = localStorage.getItem(this.cache_key_daily_before);
      let riBeforeData = JSON.parse(riBeforeDataMap);
      this.content.ri = riData['title']+'\n\n'+riData['data'][xingzuo] 
                        +"\n**************************************************************\n"
                        +riBeforeData['title']+'\n\n'+riBeforeData['data'][xingzuo];
      //周
      var zhouDataMap = localStorage.getItem(this.cache_key_weekly);
      let zhouData = JSON.parse(zhouDataMap);
      //周-before
      var zhouBeforeDataMap = localStorage.getItem(this.cache_key_weekly_before);
      let zhouBeforeData = JSON.parse(zhouBeforeDataMap);
      this.content.zhou = zhouData['title']+'\n\n'+zhouData['data'][xingzuo]
                          +"\n**************************************************************\n"
                          +zhouBeforeData['title']+'\n\n'+zhouBeforeData['data'][xingzuo];
      //月
      this.content.yue=localStorage.getItem(this.cache_key_monthly);
      //年
      this.content.nian=localStorage.getItem(this.cache_key_yearly);
    },
    getXingZuoData(xingzuo) {
      //get from local
      console.log('getXingZuoData\t'+xingzuo);
      this.getLocalData(xingzuo);
    },
  },
  created() {
    var xingzuo = this.getDefaultXingZuoSelectedValue();
    this.form.xingzuoSelect = xingzuo;
    this.getXingZuoData(xingzuo);
  },
};
</script>

<style scoped></style>
